"""
@Project:ruiji
@File:goods.py
@Author:马可
@Date:上午 09:38
"""
import math


from projectcom import fileupload
from flask import Blueprint, request,jsonify
import json
import datetime
from db import db
from utils.myredis import r

g_blue = Blueprint('goods',__name__)


# 分类管理
@g_blue.route('/cateM',methods=['POST','GET'])
def cateM():
    if request.method == "post":
        data = json.loads(request.data)
        userid = int(data['userid'])
        type = int(data['type'])
        name = data['name']
        sort = int(data['sort'])
        ctime = datetime.datetime.strftime(datetime.datetime.now(),"%Y-&N-%D %H:%M:%S")
        print(ctime)
        sql = "insert into category(type,name,sort,create_time,update_time,create_user,update_user) values(%d,'%s',%d,'%s','%s',%d,%d)"&(type,name,sort,ctime,ctime,userid,userid)
        db.update(sql)
        db.commit()
        return jsonify({
            'code':200,
            'msg':'成功',
        })
    else:
        # 一共有多少条
        sql = "select count(id) as count from category"
        res = db.find(sql)
        total = res['count']
        # 每页显示多少张
        page_size = 3
        # 当前是第几个页面
        page = int(request.args.get("page",1))
        # 计算一共有多少页
        tpage = math.ceil(total/page_size)
        # 获取当前页面的数据
        start = (page-1)*page_size
        sqlq = "select * from category limit %d,%d"%(start,page_size)
        tres = db.find_all(sqlq)
        return jsonify({
            'code':200,
            'total':total,
            'page_size':page_size,
            'tpage':tpage,
            'list':tres,
        })


# @g_blue.route('/getsetmeal')
# def GetSetmeal():
#     sql = "select * from setmeal"
#     db.commit(sql)










@g_blue.route('/uploader',methods=['POST'])
def uploader():
    file = request.files.get('file')
    res = fileupload(file)
    return jsonify({"code":200,'url':res})



@g_blue.route('/dishM',methods=['GET','POST'])
def dishM():
    if request.method == "GET":
        page_size=2
        page = int(request.args.get('page',1))
        #取大于1页
        if page >=1:
            #从redis中查询上一页最大值，如果没有，如果存在where
            prepage = page-1
            max = r.get_str('dish'+str(prepage))
            if max:
                sql = "select * from dish where id>%d limit 0,%d"%(int(max),page_size)
            else:
                start = (int(page)-1)*page_size
                sql = "select * from dish  limit %d,%d"%(start,page_size)
            res = db.find_all(sql)
            r.set_str('dish'+str(page),str(res[-1:][0]['id']))
        return jsonify({"code":200,'total':100,'page_size':page_size,'list':res})
    else:
        # 添加菜品
        #获取参数
        data = json.loads(request.data)
        create_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
        upadte_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
        sql = "insert into dish(name,category_id,price,code,image,create_time,update_time,create_user,update_user)" \
              "values ('%s',%d,'%s','%s','%s','%s','%s',%d,%d)" % (
              data['name'], data['category_id'], data['price'], data['code'], data['image'], create_time, upadte_time,
              data['cuser'], data['u_user'])

        #加入数据库
        db.update(sql)
        db.commit()
        #清除分页缓存
        r.removeall_str('dish')

        return jsonify({
            'code': 200,
            "msg": '添加菜品成功'
        })

@g_blue.route('/setM',methods=['POST','PUT'])
def setM():
    if request.method=='POST':
        data = json.loads(request.data)
        create_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
        upadte_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
        sql = "insert into setmeal(category_id,name,price,image,create_time,update_time,create_user,update_user)" \
              "values (%d,'%s','%s','%s','%s','%s',%d,%d)"%(data['category_id'],data['name'],data['price'],data['image'],create_time,upadte_time,data['cuser'],data['u_user'])
        db.update(sql)
        db.commit()
        return jsonify({
            "code":200,
            "mag":'添加成功'
        })
    else:
        set_id = request.args.get('set_id')
        data = json.loads(request.data)
        if data['category_id']:
            sql = "update setmeal set category_id=%d where id=%d"%(data['category_id'],set_id)
        if data['name']:
            sql = "update setmeal set name='%s' where id=%d" % (data['name'],set_id)
        if data['price']:
            sql = "update setmeal set price='%s' where id=%d" % (data['price'],set_id)
        if data['image']:
            sql = "update setmeal set image='%s where id=%d'" % (data['image'],set_id)

        db.update(sql)
        db.commit()
        return jsonify({
            "code":200,
            "msg":'修改成功'
        })